package com.snakegame.controller;

import com.snakegame.dto.GameResultRequest;
import com.snakegame.entity.GameRecord;
import com.snakegame.service.AuthService;
import com.snakegame.service.GameRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/game")
@CrossOrigin(origins = "*", maxAge = 3600)
public class GameController {

    @Autowired
    private GameRecordService gameRecordService;

    @Autowired
    private AuthService authService;

    @PostMapping("/result")
    public ResponseEntity<?> saveGameResult(@Valid @RequestBody GameResultRequest gameResultRequest) {
        try {
            String username = authService.getCurrentUsername();
            GameRecord gameRecord = gameRecordService.saveGameResult(username, gameResultRequest);
            return ResponseEntity.ok(gameRecord);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/my-records")
    public ResponseEntity<?> getMyGameRecords() {
        try {
            String username = authService.getCurrentUsername();
            List<GameRecord> records = gameRecordService.getUserGameRecords(username);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/my-best-scores")
    public ResponseEntity<?> getMyBestScores() {
        try {
            String username = authService.getCurrentUsername();
            List<GameRecord> records = gameRecordService.getUserBestScores(username);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/top-scores")
    public ResponseEntity<?> getTopScores() {
        try {
            List<GameRecord> records = gameRecordService.getTopScores();
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}